package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.config.LocalDateTimeConfig;
import com.xuecheng.learning.mapper.CourseTablesMapper;
import com.xuecheng.learning.model.dto.CourseTablesDto;
import com.xuecheng.learning.model.po.ChooseCourse;
import com.xuecheng.learning.model.po.CourseTables;
import com.xuecheng.learning.service.ChooseCourseService;
import com.xuecheng.learning.service.CourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class CourseTablesServiceImpl extends ServiceImpl<CourseTablesMapper,
        CourseTables> implements CourseTablesService {
    private final LocalDateTimeConfig localDateTimeConfig;

    @Autowired
    ChooseCourseService chooseCourseService;

    public CourseTablesServiceImpl(LocalDateTimeConfig localDateTimeConfig) {
        this.localDateTimeConfig = localDateTimeConfig;
    }

    /**
     * 获取课程的学习资格
     * @param userId
     * @param courseId
     * @return
     */
    @Override
    public CourseTablesDto getLearnStatus(Long userId, Long courseId) {
        CourseTables tables = getOne(new LambdaQueryWrapper<CourseTables>()
                .eq(CourseTables::getUserId,userId)
                .eq(CourseTables::getCourseId,courseId));
        CourseTablesDto dto = new CourseTablesDto();
        if(tables == null){
            dto.setLearnStatus("702002");
            return dto;
        }
        BeanUtils.copyProperties(tables,dto);
        if(LocalDateTime.now().isAfter(dto.getValidtimeEnd())){
            dto.setLearnStatus("702003");
        }else{
            dto.setLearnStatus("702001");
        }
        return dto;
    }

    /**
     * 根据选课记录id成功添加选课
     * @param chooseCourseId
     * @return
     */
    @Transactional
    @Override
    public boolean saveChooseCourseSuccess(Long chooseCourseId) {
        //根据选课记录id查询对应的选课记录
        ChooseCourse chooseCourse = chooseCourseService.getById(chooseCourseId);
        if(chooseCourse == null){
            log.info("收到支付结果通知没有查询到关联的选课记录,chooseCourseId:{}",chooseCourseId);
        }
        chooseCourse.setStatus("701001");
        chooseCourseService.updateById(chooseCourse);
        chooseCourseService.addCourseTables(chooseCourse);
        log.info("学习中心服务接收支付结果，添加选课成功，chooseCourseId：{}",chooseCourseId);
        return true;
    }
}
